source("commonmethods.R")


chiWhi<-function(X,useRank=TRUE,top=50,eps=NULL,iterations=10,debug=F) {
	
	X1=X #[0:20,]
	n=nrow(X1)

	# convert Points to distance-matrix
	dm<-as.matrix(dist(X1))

	# convert from dissimilarity to similarity 
	dm1=1/dm

	# replace n.d. values with zero
	dm1[dm1==Inf]=0

	if( useRank ) {
		# target zero-matrix of size n x n
		dm2<-zeros(n)
		# rowwise
		for(r in 1:n) {
			# sort elements and take 'top'-biggest
			topIdxs=order(-dm1[,r])[1:top]
	
			# copy topIdxs Values to target, by row and column
			dm2[topIdxs,r]=dm1[topIdxs,r]
			dm2[r,topIdxs]=dm1[r,topIdxs]
		}
		dm1=dm2
	} else {
		m=1/eps
		dm1[dm1<m]=0
	}

	# init colors: every point got its own color
	cols=1:n
	ng<-data.frame()
	for(i in 1:iterations) {
		# randomize pick a point
		for(p in sample(1:n,n,replace=FALSE)) { 
			# index of neighbors
			ngindex <- which(dm1[p,]>0)
			# indexes, values, cols
			ng<-data.frame(idx=ngindex, val=dm1[p,ngindex], col=cols[ngindex])
			
			# all reachable colors
			poscols <- unique(ng$col)

			# rank-vector indexed per color
			colval <- numeric(length(poscols))
			# for all colors: sum rank per color
			for( ci in poscols) {
				colval[ci] = sum(ng$val[which(ng$col==ci)])
			}

			if(length(colval)>0) {
			#	cat("cols[",p,"]=",cols[p],"=>",which.max(colval),"\n")
				cols[p]=which.max(colval)
			}
				
		}
		if(debug) cat("#",i," ",cols,"\n")
	}

 cols=renumber(cols)
 cols
}
